<template>
  <div class="tinymce-container editor-container" :class="{fullscreen:fullscreen}">
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <div class="editor-custom-btn-container">
      <!--      <transblock color="#1890ff" :id="tinymceId" class="editor-upload-btn" @successCBK="TransblockSuccessCBK"></transblock>-->
      <el-button v-if="duplicateResults.length > 0 || htmlresult.length > 0" type="text" title="查看AI分析结果" @click="duplicateCheckVisible=true">
        AI分析结果 </el-button>
      <aicontent :id="tinymceId" color="#1890ff" class="editor-upload-btn" @successCBK="openAiSuccessCBK" />
      <el-popover
        placement="top-start"
        title="prompts模板提示"
        width="200"
        trigger="click"
        content="关键词:selected_content"
      >
        <span slot="reference"><i class="el-icon-info" style="font-size: 10px;" /></span>
      </el-popover>
      <!--      <makerandomarticle color="#1890ff" class="editor-upload-btn" @successCBK="contentimportSuccessCBK" ></makerandomarticle>-->
      <gallery color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
      <editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
      <crmfilesmanager color="#1890ff" class="editor-upload-btn" @insert="handleInsertFile" />
      <el-drawer
        title="内容翻译"
        :visible.sync="showTransDrawer"
        direction="rtl"
        append-to-body
        size="500px"
        @close="transForm.targetLang='';"
      >
        <div class="p-4" style="margin: 10px">
          <el-form :model="transForm">
            <el-form-item label="目标语言">
              <el-select v-model="transForm.targetLang" placeholder="选择语言" @change="doTranslate">
                <el-option label="English" value="en" />
                <el-option label="中文" value="zh" />
                <el-option label="日本語" value="ja" />
                <el-option label="한국어" value="ko" />
                <el-option label="Español" value="es" />
                <el-option label="Français" value="fr" />
                <el-option label="Deutsch" value="de" />
              </el-select>
            </el-form-item>

            <el-form-item label="原文">
              <el-input v-model="transForm.original" type="textarea" readonly rows="4" />
            </el-form-item>

            <el-form-item label="译文">
              <el-input v-model="transForm.translated" type="textarea" readonly rows="4" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" :loading="translating" @click="doTranslate">
                翻译
              </el-button>
              <el-button type="success" :disabled="!transForm.translated" @click="insertTranslation">
                插入翻译
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>
      <el-drawer
        title="AI分析结果"
        :visible.sync="duplicateCheckVisible"
        direction="rtl"
        size="500px"
      >
        <div class="p-4" style="margin: 10px;">
          <template v-if="duplicateResults.length">
            <div v-for="(result, index) in duplicateResults" :key="index" class="mb-4">
              <div class="bg-gray-100 p-3 rounded mb-2">
                <div class="mb-2">
                  <strong>位置：</strong>
                  <span>{{ result.position }}</span>
                </div>
                <div class="mb-2">
                  <strong>相似度：</strong>
                  <span>{{ result.similarity }}%</span>
                </div>
                <div class="mb-2">
                  <strong>原文：</strong>
                  <div class="p-2 bg-white rounded">{{ result.original }}</div>
                </div>
                <div class="mb-2">
                  <strong>重复内容：</strong>
                  <div class="p-2 bg-white rounded">{{ result.duplicate }}</div>
                </div>
                <div>
                  <strong>改写建议：</strong>
                  <div class="p-2 bg-white rounded">{{ result.suggestion }}</div>
                </div>
              </div>
            </div>
          </template>
          <template v-else-if="htmlresult">
            <div v-html="htmlresult" />
          </template>
          <template v-else>
            <div class="text-center text-gray-500">
              未发现重复内容
            </div>
          </template>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import editorImage from './components/EditorImage'
import { Post as GetAiContent } from '@/api/cms/openai'
import contentimport from './components/contentimport'
import plugins from './plugins'
import toolbar from './toolbar'
import Transblock from './components/transblock'
import Makerandomarticle from './components/makerandomarticle'
import Aicontent from '../aicontent'
import Crmfilesmanager from '../crmfilesmanager'
import gallery from '../gallery'
import { Post as UploadBase64Image } from '@/api/cms/image'
import load from './dynamicLoadScript'

// 使用稳定的CDN版本
const tinymceCDN = 'https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.9.11/tinymce.min.js'

export default {
  name: 'Tinymce',
  components: { Crmfilesmanager, Aicontent, Makerandomarticle, Transblock, editorImage, gallery, contentimport },
  props: {
    id: {
      type: String
    },
    value: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      required: false,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    uploadDirectory: {
      type: Number,
      default: -1
    },
    uploadKeyword: {
      type: String,
      default: ''
    },
    menubar: {
      default: 'file edit insert view format table'
    },
    height: {
      type: Number,
      required: false,
      default: 360
    }
  },
  data() {
    return {
      duplicateCheckVisible: false,
      duplicateResults: [],
      htmlresult: '',
      hasChange: false,
      hasInit: false,
      tinymceId: this.id || 'vue-tinymce-' + +new Date(),
      fullscreen: false,
      showTransDrawer: false,
      translating: false,
      transForm: {
        targetLang: '',
        original: '',
        translated: ''
      }
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || ''))
      }
    }
  },
  mounted() {
    this.init()
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.duplicateResults = []
    this.destroyTinymce()
  },
  methods: {
    init() {
      // 动态加载TinyMCE CDN
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        this.initTinymce()
      })
    },
    initTinymce() {
      const _this = this
      window.tinymce.init({
        font_formats: 'Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;AkrutiKndPadmini=Akpdmi-n',
        fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt',
        selector: `#${this.tinymceId}`,
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        valid_elements: '*[*]', // 允许所有元素和所有属性
        extended_valid_elements: 'script[src|type|async|defer|charset]', // 允许 script 标签及其属性
        content_security_policy: "default-src *; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline';",
        etd_file_name: 'erp-export',
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        autosave_ask_before_unload: false,
        autosave_interval: '5s',
        paste_data_images: true,
        automatic_uploads: true,
        images_upload_handler: function(blobInfo, success, failure, progress) {
          // 显示上传进度提示
          _this.$notify({
            title: '上传中',
            message: '正在上传图片...',
            type: 'info',
            duration: 0,
            customClass: `upload-notification-${blobInfo.id()}`
          })

          // 转换blob为base64
          const reader = new FileReader()
          reader.readAsDataURL(blobInfo.blob())
          reader.onload = () => {
            const base64Data = reader.result

            // 调用上传接口
            UploadBase64Image({
              file_data: base64Data,
              directory_id: -1, // 如果需要指定目录,可以通过props传入
              keyword: '' // 如果需要关键词,可以通过props传入
            })
              .then(response => {
                // 上传成功处理
                _this.$notify.closeAll()
                _this.$notify({
                  title: '成功',
                  message: '图片上传成功',
                  type: 'success',
                  duration: 2000
                })

                // 使用返回的URL更新编辑器图片
                success(response.data.url)
              })
              .catch(error => {
                // 上传失败处理
                _this.$notify.closeAll()
                _this.$notify({
                  title: '错误',
                  message: '图片上传失败: ' + (error.message || '未知错误'),
                  type: 'error',
                  duration: 3000
                })

                failure('图片上传失败: ' + (error.message || '未知错误'))
              })
          }
        },

        rel_list: [
          { title: 'None', value: '' },
          { title: 'No Follow', value: 'nofollow' }
        ],
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        contextmenu: 'AIImageSearch createAIImage', // 使用自定义右键菜单
        setup(editor) {
          // 重写内容
          editor.addMenuItem('aiRewrite', {
            text: 'AI重写内容',
            icon: 'warning',
            context: 'tools',
            onclick: function() {
              _this.handleAiRewrite()
            }
          })
          // 添加重复内容检查菜单项
          editor.addMenuItem('checkDuplicates', {
            text: 'AI检查重复内容',
            icon: 'warning',
            context: 'tools',
            onclick: function() {
              _this.handleDuplicateCheck()
            }
          })
          // 内容质量分析
          editor.addMenuItem('checkContentQuanlity', {
            text: 'EEAT检查内容质量',
            icon: 'warning',
            context: 'tools',
            onclick: function() {
              _this.handlecheckContentQuanlity()
            }
          })
          editor.addMenuItem('AIImageSearch', {
            text: 'AI搜索图片',
            icon: 'search',
            context: 'tools',
            onclick: function() {
              // 获取选中的内容
              const selectedText = editor.selection.getContent({ format: 'text' })
              if (selectedText) {
                _this.handleSearch(selectedText)
              } else {
                _this.$message.warning('请先选中要搜索的文本！')
              }
            }
          })
          // 添加 Google 图片搜索菜单项
          editor.addMenuItem('googleImageSearch', {
            text: 'Google搜索图片',
            icon: 'search',
            context: 'tools',
            onclick: function() {
              const selectedText = editor.selection.getContent({ format: 'text' })
              if (selectedText) {
                _this.handleGoogleImageSearch(selectedText)
              } else {
                _this.$message.warning('请先选中要搜索的文本！')
              }
            }
          })
          // 添加 Google 图片搜索菜单项
          editor.addMenuItem('imagestock', {
            text: '图库搜素',
            icon: 'search',
            context: 'tools',
            onclick: function() {
              const selectedText = editor.selection.getContent({ format: 'text' })
              if (selectedText) {
                _this.handleImageSearch(selectedText, 'shutterstock')
              } else {
                _this.$message.warning('请先选中要搜索的文本！')
              }
            }
          })
          editor.addMenuItem('firstPersonRewrite', {
            text: '第一人称&经验优化',
            icon: 'paragraph',
            context: 'tools',
            onclick: function() {
              _this.handleFirstPersonRewrite()
            }
          })
          editor.addMenuItem('techtoexample', {
            text: '技术转为为案例',
            icon: 'paragraph',
            context: 'tools',
            onclick: function() {
              _this.handleTechToExampleRewrite()
            }
          })
          editor.addMenuItem('translatetable', {
            text: '转成表格',
            icon: 'comment',
            context: 'tools',
            onclick: function() {
              _this.handleTranslateToTable()
            }
          })
          editor.addMenuItem('expertopinion', {
            text: '专家意见',
            icon: 'comment',
            context: 'tools',
            onclick: function() {
              _this.handleInsertExpertOpinionPlaceholder()
            }
          })

          // 添加扩写段落菜单
          editor.addMenuItem('expandParagraph', {
            text: 'AI段落扩写',
            icon: 'paragraph',
            context: 'tools',
            onclick: function() {
              _this.handleExpandParagraph()
            }
          })
          // 添加AI写开头菜单
          editor.addMenuItem('aiWriteIntro', {
            text: 'AI写开头',
            icon: 'paste-row-before',
            context: 'tools',
            onclick: function() {
              _this.handleAIIntro()
            }
          })
          // 添加AI写结尾菜单
          editor.addMenuItem('aiWriteEnding', {
            text: 'AI写结尾',
            icon: 'paste-row-after',
            context: 'tools',
            onclick: function() {
              _this.handleAIEnding()
            }
          })
          editor.addMenuItem('translateContent', {
            text: '翻译选择内容',
            icon: 'translate',
            context: 'tools',
            onclick: function() {
              _this.handleTranslate()
            }
          })
          // 清理空行和没有内容的空白区域
          editor.addMenuItem('clearEmptyParagraphs', {
            text: '清理空行和空白区域',
            icon: 'trash',
            context: 'tools',
            onclick: function() {
              _this.clearEmptyParagraphs(editor)
            }
          })
          // 根据权限判断是否添加AI图片生成菜单
          if (_this.$store.getters.roles.indexOf('ai_image_user') !== -1) {
            editor.addMenuItem('createAIImage', {
              text: '创建AI图片',
              icon: 'image',
              context: 'tools',
              onclick: function() {
                const imageId = 'ai-image-' + Date.now()
                editor.insertContent(`<img class='ai-generating-image' id='${imageId}' src="https://tools.kikimami.com/static/img/placeholder.png" />`)
                _this.$message.warning('添加完毕之后点击优化图片才会在后台生成')
              }
            })
            // 有权限时显示两个菜单项
            editor.settings.contextmenu = 'imagestock AIImageSearch googleImageSearch translateContent firstPersonRewrite techtoexample translatetable expertopinion aiWriteIntro aiWriteEnding expandParagraph createAIImage aiRewrite checkContentQuanlity checkDuplicates | clearEmptyParagraphs copy paste'
          } else {
            // 没有权限时只显示搜索菜单项
            editor.settings.contextmenu = 'imagestock AIImageSearch googleImageSearch translateContent firstPersonRewrite techtoexample translatetable expertopinion aiWriteIntro aiWriteEnding expandParagraph aiRewrite checkContentQuanlity checkDuplicates | clearEmptyParagraphs copy paste'
          }
          // 确保在初始化时包含自定义菜单项
          // editor.on('init', function() {
          //   editor.settings.contextmenu = 'AIImageSearch ' + (editor.settings.contextmenu || 'link image inserttable | cell row column deletetable');
          // });
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })

          // 添加上传开始和结束的视觉反馈
          editor.on('BeforeImageUpload', function(e) {
            const img = e.target
            img.classList.add('uploading-image')
          })

          editor.on('ImageUploadComplete', function(e) {
            const img = e.target
            img.classList.remove('uploading-image')
          })
        },
        // 添加上传相关的样式
        content_style: `
      .uploading-image {
        opacity: 0.6;
        filter: grayscale(100%);
        border: 2px dashed #ccc;
      }
      img {
        max-width: 100%;
        height: auto;
      }
    `
        // 整合七牛上传
        // images_dataimg_filter(img) {
        //   setTimeout(() => {
        //     const $image = $(img);
        //     $image.removeAttr('width');
        //     $image.removeAttr('height');
        //     if ($image[0].height && $image[0].width) {
        //       $image.attr('data-wscntype', 'image');
        //       $image.attr('data-wscnh', $image[0].height);
        //       $image.attr('data-wscnw', $image[0].width);
        //       $image.addClass('wscnph');
        //     }
        //   }, 0);
        //   return img
        // },
        // images_upload_handler(blobInfo, success, failure, progress) {
        //   progress(0);
        //   const token = _this.$store.getters.token;
        //   getToken(token).then(response => {
        //     const url = response.data.qiniu_url;
        //     const formData = new FormData();
        //     formData.append('token', response.data.qiniu_token);
        //     formData.append('key', response.data.qiniu_key);
        //     formData.append('file', blobInfo.blob(), url);
        //     upload(formData).then(() => {
        //       success(url);
        //       progress(100);
        //     })
        //   }).catch(err => {
        //     failure('出现未知问题，刷新页面，或者联系程序员')
        //     console.log(err);
        //   });
        // },
      })
    },
    clearEmptyParagraphs() {
      const editor = window.tinymce.get(this.tinymceId)
      const content = editor.getContent()
      let cleanedContent = content.replace(/<p><\/p>/g, '')
      // 清理<p>&nbsp;</p>
      cleanedContent = cleanedContent.replace(/<p>&nbsp;<\/p>/g, '')
      // 清理空<h3></h3>
      cleanedContent = cleanedContent.replace(/<h3><\/h3>/g, '')
      const deletedCount = (content.match(/<p><\/p>/g) || []).length
      editor.setContent(cleanedContent)
      // 在清理完成后，显示通知
      if (deletedCount > 0) {
        this.$notify({
          title: '清理完成',
          message: `已清理 ${deletedCount} 个空白区域`,
          type: 'success',
          duration: 2000
        })
      } else {
        this.$notify({
          title: '无空白区域',
          message: '未发现空行或空白区域。',
          type: 'info',
          duration: 2000
        })
      }
    },
    handlecheckContentQuanlity() {
      const editor = window.tinymce.get(this.tinymceId)
      const content = editor.getContent()

      this.$notify({
        title: '处理中',
        message: 'AI 正在思考...',
        type: 'info',
        duration: 0
      })

      GetAiContent({
        aiprompt_id: '272',
        kvs: [{ 'content': content, 'title': this.title }],
        engine: 'o3-mini',
        prompt_name: 'check_content_quality',
        humanway: false
      }).then(response => {
        this.$notify.closeAll()
        if (response && response.content) {
          this.$notify({
            title: '成功',
            message: 'AI判断内容质量完成',
            type: 'success'
          })
          this.htmlresult = response.content
          this.duplicateCheckVisible = true
        }
      }).catch(error => {
        this.$notify.closeAll()
        this.$notify({
          title: '错误',
          message: 'AI判断内容质量失败：' + (error.message || '未知错误'),
          type: 'error'
        })
      })
    },
    handleAiRewrite() {
      const editor = window.tinymce.get(this.tinymceId)
      const rich_content = editor.getContent()
      this.$notify({
        title: '处理中',
        message: 'AI正在优化内容...',
        type: 'info',
        duration: 0
      })
      GetAiContent({
        kvs: [{ 'rich_content': rich_content, 'title': this.title }],
        aiprompt_id: '278',
        prompt_name: 'ai_rewrite',
        humanway: false, // 去AI优化
        keywords: []
      }).then(response => {
      // 关闭所有通知
        this.$notify.closeAll()

        if (response && response.content) {
        // 在文章末尾插入 AI 生成的内容
          editor.setContent(response.content)
          this.$notify({
            title: '成功',
            message: '内容已经重写',
            type: 'success'
          })
        }
      })
    },
    handleDuplicateCheck() {
      const editor = window.tinymce.get(this.tinymceId)
      const textContent = editor.getContent({ format: 'text' })
      this.$notify({
        title: '处理中',
        message: 'AI正在检查重复内容,请稍候...',
        type: 'info',
        duration: 0
      })

      const prompt = `分析以下文章中的重复内容:
# 要求
1. 逐段对比分析,仅分析纯文本内容
2. 标记相似度或者表达意思相似超过50%的段落
3. 指出重复位置和重复程度
4. 给出定位重复位置的搜索关键词
5. 给出改写参考内容（注意不是建议）

# 文章内容
[article]${textContent}[/article]

# 输出格式
不要带有代码块标记,直接返回JSON：
{
 "duplicates": [
   {
     "original": "原始段落文本",
     "duplicate": "重复段落文本",
     "similarity": "90",
     "position": "段落2和段落5",
     “定位关键词": "berunwear",
     "rewrite": "改写的内容"
   }
 ]
}`

      GetAiContent({
        prompt,
        engine: 'gpt-4o',
        prompt_name: 'duplicate_check'
      }).then(response => {
        try {
          const cleanContent = response.original_content
            .replace(/<[^>]*>/g, '')
            .replace(/```json\n|\n```/g, '')

          const result = JSON.parse(cleanContent)
          this.duplicateResults = result.duplicates
          this.duplicateCheckVisible = true

          this.$notify.closeAll()
          this.$notify({
            title: '检查完成',
            message: `发现 ${result.duplicates.length} 处重复内容`,
            type: 'success'
          })
        } catch (error) {
          console.error('处理失败:', error)
          this.$notify.closeAll()
          this.$notify({
            title: '错误',
            message: '处理失败: ' + error.message,
            type: 'error'
          })
        }
      })
    },
    handleTranslate() {
      const editor = window.tinymce.get(this.tinymceId)
      const selectedText = editor.selection.getContent()

      if (!selectedText) {
        this.$message.warning('请先选择需要翻译的文本！')
        return
      }

      this.transForm.original = selectedText
      this.showTransDrawer = true
    },

    doTranslate() {
      if (!this.transForm.targetLang) {
        this.$message.warning('请选择目标语言！')
        return
      }

      this.translating = true

      const prompt = `Please translate the following original text to ${this.transForm.targetLang}:
     # Requirements
     1. Maintain the original meaning and tone
     2. Use natural expressions in the target language
     3. Keep any technical terms accurate
     4. Preserve formatting if present
     5. don't include the '<original>' tag in the output

     # Text to translate
     <original>${this.transForm.original}</original>

     # Output format
     Direct translation only, no explanations.`

      GetAiContent({
        prompt,
        engine: 'gpt-4o',
        prompt_name: 'translate_content',
        humanway: false
      }).then(response => {
        this.transForm.translated = response.content
      }).finally(() => {
        this.translating = false
      })
    },

    insertTranslation() {
      const editor = window.tinymce.get(this.tinymceId)
      editor.selection.setContent(this.transForm.translated)
      this.showTransDrawer = false
      this.transForm.translated = ''
    },
    // 添加 Google 图片搜索处理函数
    handleGoogleImageSearch(selectedText) {
      const searchQuery = `${selectedText}` // 组合搜索关键词
      const searchUrl = `https://www.google.com/search?q=${encodeURIComponent(searchQuery)}&tbm=isch`
      window.open(searchUrl, '_blank')
    },
    // 第三方搜索图片
    handleImageSearch(selectedText, task) {
      const searchQuery = `${selectedText}` // 组合搜索关键词
      if (!task) {
        task = 'google'
      }
      let searchUrl = `https://www.google.com/search?q=${encodeURIComponent(searchQuery)}&tbm=isch`
      switch (task) {
        case 'google':
          searchUrl = `https://www.google.com/search?q=${encodeURIComponent(searchQuery)}&tbm=isch`
          window.open(searchUrl, '_blank')
          break
        case 'bing':
          searchUrl = `https://www.bing.com/images/search?q=${encodeURIComponent(searchQuery)}`
          window.open(searchUrl, '_blank')
          break
        case 'baidu':
          searchUrl = `https://image.baidu.com/search/index?tn=baiduimage&word=${encodeURIComponent(searchQuery)}`
          window.open(searchUrl, '_blank')
          break
        case 'shutterstock':
          searchUrl = `https://www.shutterstock.com/search/${encodeURIComponent(searchQuery)}`
          window.open(searchUrl, '_blank')
          break
        default:
          break
      }
    },
    handleAIEnding() {
      const editor = window.tinymce.get(this.tinymceId)
      const currentContent = editor.getContent({ format: 'text' })
      // const prompt = `请为以下文章创作一段精彩的结尾：
      // # 要求
      // 1. 长度控制在50-80字之间
      // 2. 使用简单的日常用语，避免复杂难懂的词汇
      // 3. 语气要自然流畅，总结性强
      // 4. 要与文章主题紧密相关
      // 5. 要有启发性和深度，给读者留下思考空间
      // 6. 请使用文章内容中的语言，通常是英文
      // # 文章内容
      // ${currentContent}
      // # 文章标题
      // ${this.title}
      // # 输出格式
      // 直接输出结尾文字，不需要任何解释或额外格式。`;
      this.$notify({
        title: '处理中',
        message: 'AI正在改写结尾...',
        type: 'info',
        duration: 0
      })
      GetAiContent({
        engine: 'gpt-4.1',
        kvs: [{ 'content': currentContent, 'title': this.title }],
        aiprompt_id: '258',
        prompt_name: 'ai_post_ending',
        humanway: true, // 去AI优化
        keywords: []
      }).then(response => {
      // 关闭所有通知
        this.$notify.closeAll()

        if (response && response.content) {
        // 在文章末尾插入 AI 生成的内容
          editor.setContent(editor.getContent() + '\n\n' + '<h2>summary</h2>' + response.content)

          this.$notify({
            title: '成功',
            message: '结尾已添加到文章末尾',
            type: 'success'
          })
        }
      })
    },
    handleInsertExpertOpinionPlaceholder() {
      // 生成唯一ID，避免多个占位时混淆
      const placeholderId = 'expert-say-' + Date.now()

      const snippet = `<p id="${placeholderId}">专家说生成中....</p>`
      // 在光标处插入占位标签
      window.tinymce.get(this.tinymceId).insertContent(snippet)
      this.handleInsertAdContent(snippet)
    },
    handleInsertAdContent(target_snippet) {
      const editor = window.tinymce.get(this.tinymceId)
      const content = editor.getContent()
      if (!target_snippet) {
        this.$message.warning('没有发现要插入的内容')
        return
      }

      this.$notify({
        title: '处理中',
        message: 'AI 正在思考...',
        type: 'info',
        duration: 0
      })

      GetAiContent({
        aiprompt_id: '251',
        kvs: [{ 'content': content, 'target_snippet': target_snippet }],
        engine: 'gpt-4.1',
        prompt_name: 'insert_ai_content',
        humanway: true
      }).then(response => {
        this.$notify.closeAll()

        if (response && response.content) {
          const new_content = content.replace(target_snippet, response.content)
          editor.setContent(new_content)
          this.$notify({
            title: '成功',
            message: '增加专家观点成功',
            type: 'success'
          })
        }
      }).catch(error => {
        this.$notify.closeAll()
        this.$notify({
          title: '错误',
          message: '增加专家观点失败：' + (error.message || '未知错误'),
          type: 'error'
        })
      })
    },
    handleTranslateToTable() {
      const editor = window.tinymce.get(this.tinymceId)
      const selectedText = editor.selection.getContent()

      if (!selectedText) {
        this.$message.warning('请先选中需要的文本！')
        return
      }

      this.$notify({
        title: '处理中',
        message: 'AI 正在进行表格转化改写...',
        type: 'info',
        duration: 0
      })

      GetAiContent({
        aiprompt_id: '257',
        kvs: [{ 'content': selectedText }],
        engine: 'gpt-4.1',
        prompt_name: 'table_rewrite',
        humanway: false
      }).then(response => {
        this.$notify.closeAll()

        if (response && response.content) {
          editor.selection.setContent(response.content)
          this.$notify({
            title: '成功',
            message: '表格转化完成',
            type: 'success'
          })
        }
      }).catch(error => {
        this.$notify.closeAll()
        this.$notify({
          title: '错误',
          message: '表格转化失败：' + (error.message || '未知错误'),
          type: 'error'
        })
      })
    },
    handleFirstPersonRewrite() {
      const editor = window.tinymce.get(this.tinymceId)
      const selectedText = editor.selection.getContent({ format: 'text' })

      if (!selectedText) {
        this.$message.warning('请先选中需要第一人称改写的文本！')
        return
      }

      this.$notify({
        title: '处理中',
        message: 'AI 正在进行第一人称改写...',
        type: 'info',
        duration: 0
      })

      GetAiContent({
        aiprompt_id: '250',
        kvs: [{ 'content': selectedText }],
        engine: 'gpt-4.1',
        prompt_name: 'first_person_rewrite',
        humanway: true
      }).then(response => {
        this.$notify.closeAll()

        if (response && response.content) {
          editor.selection.setContent(response.content)
          this.$notify({
            title: '成功',
            message: '第一人称改写完成',
            type: 'success'
          })
        }
      }).catch(error => {
        this.$notify.closeAll()
        this.$notify({
          title: '错误',
          message: '第一人称改写失败：' + (error.message || '未知错误'),
          type: 'error'
        })
      })
    },
    handleTechToExampleRewrite() {
      const editor = window.tinymce.get(this.tinymceId)
      const selectedText = editor.selection.getContent({ format: 'text' })

      if (!selectedText) {
        this.$message.warning('请先选中需要改写的文本！')
        return
      }

      this.$notify({
        title: '处理中',
        message: 'AI正在进行 技术参数转为案例...',
        type: 'info',
        duration: 0
      })

      GetAiContent({
        aiprompt_id: '266',
        kvs: [{ 'content': selectedText }],
        engine: 'gpt-4.1',
        prompt_name: 'tech2example',
        humanway: true
      }).then(response => {
        this.$notify.closeAll()

        if (response && response.content) {
          editor.selection.setContent(response.content)
          this.$notify({
            title: '成功',
            message: '技术参数转为案例改写完成',
            type: 'success'
          })
        }
      }).catch(error => {
        this.$notify.closeAll()
        this.$notify({
          title: '错误',
          message: '技术参数转为案例改写：' + (error.message || '未知错误'),
          type: 'error'
        })
      })
    },
    handleExpandParagraph() {
      const editor = window.tinymce.get(this.tinymceId)
      const selectedText = editor.selection.getContent({ format: 'text' })
      const content = editor.getContent({ format: 'text' })
      if (!selectedText) {
        this.$message.warning('请先选择需要扩写的段落！')
        return
      }

      // const prompt = `请对以下段落进行扩写改写：
      // # 要求
      // 1. 输出的内容应该在50-80个单词之间
      // 2. 完全替换原文，但保持核心意思相同
      // 3. 加入第一人称的观点和深度思考
      // 4. 增加具体的例子或个人经历来支持观点
      // 5. 保持与原文相同的语言(英文/中文)
      // 6. 使用更生动、更有说服力的表达方式
      //
      // # 原文段落
      // ${selectedText}
      //
      // # 上下文（文章标题）
      // ${this.title}
      //
      // # 输出格式
      // 直接输出改写后的段落，不需要任何解释或额外格式。
      // 不要在开头或结尾添加任何额外的内容。`;

      this.$notify({
        title: '处理中',
        message: 'AI正在改写段落...',
        type: 'info',
        duration: 0
      })

      GetAiContent({
        // prompt: prompt,
        engine: 'gpt-4.1',
        kvs: [{ 'content': content, 'selectedText': selectedText, 'title': this.title }],
        prompt_name: 'ai_rewrite_paragraph',
        aiprompt_id: '259',
        humanway: true, // 去AI优化
        keywords: []
      }).then(response => {
        this.$notify.closeAll()

        if (response && response.content) {
        // 替换选中的内容
          editor.selection.setContent(response.content)

          this.$notify({
            title: '成功',
            message: '段落改写完成',
            type: 'success'
          })
        }
      }).catch(error => {
        this.$notify.closeAll()
        this.$notify({
          title: '错误',
          message: '段落改写失败：' + (error.message || '未知错误'),
          type: 'error'
        })
      })
    },
    handleAIIntro() {
      const editor = window.tinymce.get(this.tinymceId)
      const currentContent = editor.getContent({ format: 'text' })
      // const prompt = `请为以下文章创作一段引人入胜的开场白：
      //   # 要求
      //   1. 长度控制在50-80字之间
      //   2. 使用简单的日常用语，避免复杂难懂的词汇
      //   3. 语气要自然流畅，像在跟朋友聊天
      //   4. 要与文章主题紧密相关
      //   5. 结尾要设置一个小悬念或引导语，吸引读者继续往下读
      //   6. 请使用文章内容中的语言，通常是英文
      //   # 文章内容
      //   ${currentContent}
      //   # 文章标题
      //   ${this.title}
      //   # 输出格式
      //   直接输出开场白文字，不需要任何解释或额外格式。`;
      this.$notify({
        title: '处理中',
        message: 'AI正在写开头请稍后...',
        type: 'info',
        duration: 0
      })
      GetAiContent({
        // prompt: prompt,
        engine: 'gpt-4.1',
        kvs: [{ 'content': currentContent, 'title': this.title }],
        aiprompt_id: '260',
        prompt_name: 'ai_write_intro',
        humanway: true, // 去AI优化
        keywords: []
      }).then(response => {
        // 关闭所有通知
        this.$notify.closeAll()

        if (response && response.content) {
          // 在文章开头插入 AI 生成的内容
          editor.setContent(response.content + editor.getContent())

          this.$notify({
            title: '成功',
            message: '开场白已添加到文章开头',
            type: 'success'
          })
        }
      })
    },
    handleSearch(selectedText) {
    // 替换为你的实际搜索逻辑
      const prompt = 'help me search the image of the subtitle of the article.\n' + 'subtitle: ' + selectedText + '\n' + 'article: ' + this.title
      const searchUrl = `https://www.perplexity.ai/search?source=images&q=${encodeURIComponent(prompt)}`
      window.open(searchUrl, '_blank') // 在新窗口中打开搜索结果
    },
    async uploadImage(formData) {
      try {
        const response = await this.$http({
          url: '/api/upload/image', // 替换为实际的上传接口
          method: 'POST',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        return response.data
      } catch (error) {
        throw error
      }
    },
    destroyTinymce() {
      if (window.tinymce.get(this.tinymceId)) {
        window.tinymce.get(this.tinymceId).destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    insertContent(v) {
      window.tinymce.get(this.tinymceId).insertContent(v)
    },
    getCount() {
      return window.tinymce.get(this.tinymceId).plugins.wordcount.getCount()
    },
    handleInsertFile(item) {
      const _this = this
      let code = `<a href="${item.url}" target="blank">${item.filename}</a>`
      if (item.content_type.indexOf('image') !== -1) {
        code = `<img src="${item.url}" style="width: 100%; height: auto;" ></img>`
      }
      window.tinymce.get(_this.tinymceId).insertContent(code)
    },
    imageSuccessCBK(arr) {
      const _this = this
      arr.forEach(v => {
        let style = 'width:100%; height:auto;'
        if (v.width !== undefined) {
          style += 'max-width:' + v.width + 'px' + ';'
        }
        window.tinymce.get(_this.tinymceId).insertContent(`<img src="${v.url}" style="${style}">`)
      })
    },
    TransblockSuccessCBK(content) {
      this.setContent(window.tinymce.get(this.tinymceId).getContent() + content.content)
      this.$message.success('已经添加代码到了末尾，可以查看源码')
      // window.tinymce.get(this.tinymceId).insertContent(content.content)
      // this.$emit('importcontentBGK', content)
    },
    openAiSuccessCBK(content) {
      window.tinymce.get(this.tinymceId).insertContent(content.content)
      this.$emit('importcontentBGK', content)
    },
    contentimportSuccessCBK(content) {
      window.tinymce.get(this.tinymceId).insertContent(content.content)
      this.$emit('importcontentBGK', content)
    }
  }
}
</script>

<style scoped>
.tinymce-container {
  position: relative;
}
.tinymce-container>>>.mce-fullscreen {
  z-index: 10000;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}
.editor-upload-btn {
  display: inline-block;
}
</style>
